package com.element.sentinel.exception;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.common.core.exception.code.LimitErrorCode;
import com.common.core.results.VoidResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayExceptionHandler implements BlockRequestHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange,
                                              Throwable e) {
        logger.error("网关服务限流:", e);
        VoidResult result = VoidResult.failed(LimitErrorCode.A_API_LIMIT_ERROR);
        return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(result));
    }
}